package main

import (
	_ "github.com/go-sql-driver/mysql"

	"database/sql"
	"fmt"
	"sync"
)

func main() {
	concurrency := 10000

	var wg sync.WaitGroup
	wg.Add(concurrency)
	results := make(chan int, concurrency)

	dbLink := "root:root@tcp(localhost:3307)/productions_payment"

	db, err := sql.Open("mysql", dbLink)
	if err != nil {
		panic(err)
	}
	defer func(db *sql.DB) {
		err := db.Close()
		if err != nil {
			panic(err)
		}
	}(db)

	for i := 0; i < concurrency; i++ {
		go func(id int) {
			defer wg.Done()

			row := db.QueryRow("SELECT count FROM test_counter WHERE id = ?", id)
			var count int
			err := row.Scan(&count)
			if err != nil {
				fmt.Println("读取数据失败:", err)
				return
			}

			count = count + 1
			_, err = db.Exec("UPDATE test_counter SET count = ? WHERE id = ?", count, id)
			if err != nil {
				fmt.Println("更新数据失败:", err)
				return
			}

			results <- count
		}(i)
	}

	wg.Wait()
	close(results)

	for result := range results {
		fmt.Println("更新结果:", result)
	}
}
